/**
 * 执行保养计划
 */

import React, { useEffect, useState, useCallback, useRef, useMemo } from 'react';
import { useParams, useHistory } from 'react-router-dom';
import moment from 'moment';
import { euqApplicationName, lotAuth, lotAuth2 } from '../../config';
import {
    Card,
    Modal,
    Form,
    Row,
    Col,
    Input,
    Typography,
    TreeSelect,
    DatePicker,
    InputNumber,
    Radio,
    Button,
    message,
    Spin,
} from 'antd';

import { get, post } from '../../axios/http';
import { formatTime, BasicTable } from '../../utils/x';

const { Title } = Typography;
const { TextArea } = Input;


/**
 * 保养部位 - 编辑表单
 */
const MaintenanceProgramDetailForm1Form2 = React.forwardRef(function MaintenanceProgramDetailForm1Form2({ form, form: { getFieldDecorator, setFieldsValue, getFieldValue } }, ref) {
    React.useImperativeHandle(ref, () => ({ form }));

    return (
        <Form>
            <Form.Item label="保养部位">
                {getFieldDecorator('positionName')(
                    <Input disabled />
                )}
            </Form.Item>
            <Form.Item label="保养标准">
                {getFieldDecorator('maintainStandard')(
                    <Input disabled />
                )}
            </Form.Item>
            <Form.Item label="保养">
                {getFieldDecorator('maintain')(
                    <Radio.Group>
                        <Radio value={0}>未保养</Radio>
                        <Radio value={1}>已保养</Radio>
                    </Radio.Group>
                )}
            </Form.Item>
            <Form.Item label="备注">
                {getFieldDecorator('remarks')(
                    <Input />
                )}
            </Form.Item>
            {getFieldDecorator('id')(
                <Input type="hidden" disabled />
            )}
            {getFieldDecorator('requirementId')(
                <Input type="hidden" disabled />
            )}
            {getFieldDecorator('status')(
                <Input type="hidden" disabled />
            )}
            {getFieldDecorator('typeId')(
                <Input type="hidden" disabled />
            )}
            {getFieldDecorator('typeName')(
                <Input type="hidden" disabled />
            )}
            {getFieldDecorator('_index')(
                <Input type="hidden" disabled />
            )}
        </Form>
    );
});

/**
 * 保养部位表格
 */
function MaintenanceProgramDetailForm1Table3({ data, onEvent }) {
    const handleActionClick = useCallback((e) => {
        e.preventDefault();
        switch (e.currentTarget.getAttribute('data-action')) {
            case 'delete': {
                onEvent && onEvent({ type: 'DELETE_ITEM', index: Number(e.currentTarget.getAttribute('data-index')) });
                break;
            }
            case 'edit': {
                onEvent && onEvent({ type: 'EDIT_ITEM', index: Number(e.currentTarget.getAttribute('data-index')) });
                break;
            }
            default:
                break;
        }
    }, [onEvent]);

    const tableColumns = [
        {
            title: '操作',
            render: (text, row, index) => {
                return (
                    <>
                        <a href="#" data-action="edit" data-index={index} onClick={handleActionClick}>编辑</a>
                    </>
                );
            },
        },
        {
            title: '保养部位',
            dataIndex: 'positionName',
        },
        {
            title: '保养标准',
            dataIndex: 'maintainStandard',
        },
        {
            title: '保养',
            dataIndex: 'maintain',
            render: (text, row, index) => {
                switch (text) {
                    case 0:
                        return '未保养';
                    case 1:
                        return '已保养';
                    default:
                        break;
                }
            }
        },
        {
            title: '备注',
            dataIndex: 'remarks',
        },
    ];

    return (
        <BasicTable dataSource={data} columns={tableColumns} />
    );
}

/**
 * 保养工作量 - 编辑人员表单
 */
const MaintenanceProgramDetailForm1Form1 = React.forwardRef(function MaintenanceProgramDetailForm1Form1({ form, form: { getFieldDecorator, setFieldsValue, getFieldValue } }, ref) {
    React.useImperativeHandle(ref, () => ({ form }));

    return (
        <Form>
            <Form.Item label="保养人员">
                {getFieldDecorator('personName')(
                    <Input disabled />
                )}
            </Form.Item>
            {getFieldDecorator('personId')(
                <Input type="hidden" disabled />
            )}
            <Form.Item label="开始时间">
                {getFieldDecorator('maintainStartTime')(
                    <DatePicker />
                )}
            </Form.Item>
            <Form.Item label="结束时间">
                {getFieldDecorator('maintainEndTime')(
                    <DatePicker />
                )}
            </Form.Item>
            <Form.Item label="保养用时">
                {getFieldDecorator('wastedTime')(
                    <Input />
                )}
            </Form.Item>
            <Form.Item label="内容或步骤">
                {getFieldDecorator('contentOrSteps')(
                    <Input />
                )}
            </Form.Item>
            {getFieldDecorator('id')(
                <Input type="hidden" disabled />
            )}
            {getFieldDecorator('_index')(
                <Input type="hidden" disabled />
            )}
        </Form>
    );
});

/**
 * 工单表单 - 保养负责人 - 搜索表单
 */
 function MaintenanceProgramDetailForm1Table2SearchForm({ form, form: { getFieldDecorator }, onSubmit, treeData1 }) {
    const [treeData2, setTreeData2] = useState([]);

    const handleSubmit = useCallback((e) => {
        e.preventDefault();
        form.validateFields((err, values) => {
            if (err) {
                return;
            }
            onSubmit && onSubmit(values);
        });
    }, [onSubmit]);

    const emptyItem = { title: '全部', value: null };

    useEffect(() => {
        const parseDepData = (arr) => {
            const result = [];
            for (const item of arr) {
                result.push({
                    value: item.id,
                    title: item.name,
                    children: parseDepData(item.children),
                });
            }
            return result;
        };

        (async () => {
            try {
                // const res = await get(lotAuth + '/department/queryTreeDepartment');
                const res = await get(lotAuth2 + '/department/queryTreeDepartment');
                setTreeData2(parseDepData(res.data));
            } catch (err) {}
        })();
    }, []);

    return (
        <Form layout="inline" onSubmit={handleSubmit} style={{ marginBottom: 10 }}>
            <Form.Item label="用户名称">
                {getFieldDecorator('userName')(
                    <Input />
                )}
            </Form.Item>
            <Form.Item label="执行班组">
                {getFieldDecorator('team')(
                    <TreeSelect treeData={[emptyItem, ...treeData1]} style={{ width: 120 }} />
                )}
            </Form.Item>
            <Form.Item label="使用部门">
                {getFieldDecorator('department')(
                    <TreeSelect treeData={[emptyItem, ...treeData2]} style={{ width: 120 }} />
                )}
            </Form.Item>
            <Form.Item>
                <Button type="primary" htmlType="submit">搜索</Button>
            </Form.Item>
        </Form>
    );
}

/**
 * 保养工作量 - 选择人员表格
 */
function MaintenanceProgramDetailForm1Table2({ selectedKeys, onSelectChange, treeData1 }) {
    const [data, setData] = useState([]);
    const [isDataLoading, setIsDataLoading] = useState(false);
    const [dataQuery, setDataQuery] = useState({});
    const [pagination, setPagination] = useState({});

    const tableColumns = [
        {
            title: '名称',
            dataIndex: 'userName',
        },
        {
            title: '部门',
            dataIndex: 'department',
        },
        {
            title: '班组',
            dataIndex: 'teamName',
        },
        {
            title: '职务',
            dataIndex: 'roleName',
        },
    ];
    const tableRowSelection = {
        selectedRowKeys: selectedKeys,
        onChange: onSelectChange,
    };

    const fetchData = useCallback((params = {}, exact = false) => {
        setDataQuery(exact ? params : prev => ({
            ...prev,
            ...params,
        }));
    }, []);

    const SearchFormWrap = useMemo(() => {
        return Form.create()(MaintenanceProgramDetailForm1Table2SearchForm);
    }, [treeData1]);

    const handleSearchFormSubmit = useCallback((values) => {
        fetchData(values, true);
    }, []);

    useEffect(() => {
        (async () => {
            setIsDataLoading(true);
            try {
                const res = await get(euqApplicationName + '/equipmentMaintain/findUserOfMaintain', { params: dataQuery });
                res && setData(res.data);
                setPagination({
                    current: res.pageNum,
                    pageSize: res.pageSize,
                    total: res.total,
                    onChange(page) {
                        setDataQuery(prev => ({
                            ...prev,
                            pageNum: page,
                        }));
                    },
                });
            } catch (err) {}
            setIsDataLoading(false);
        })();
    }, [dataQuery]);

    return (
        <>
            <SearchFormWrap onSubmit={handleSearchFormSubmit} treeData1={treeData1} />
            <BasicTable
                rowKey="id"
                dataSource={data}
                columns={tableColumns}
                rowSelection={tableRowSelection}
                loading={isDataLoading}
                pagination={pagination} />
        </>
    );
}


/**
 * 保养工作量表格
 */
function MaintenanceProgramDetailForm1Table1({ data, onEvent }) {
    const handleActionClick = useCallback((e) => {
        e.preventDefault();
        switch (e.currentTarget.getAttribute('data-action')) {
            case 'delete': {
                onEvent && onEvent({ type: 'DELETE_ITEM', index: Number(e.currentTarget.getAttribute('data-index')) });
                break;
            }
            case 'edit': {
                onEvent && onEvent({ type: 'EDIT_ITEM', index: Number(e.currentTarget.getAttribute('data-index')) });
                break;
            }
            default:
                break;
        }
    }, [onEvent]);

    const tableColumns = [
        {
            title: '操作',
            render: (text, row, index) => {
                return (
                    <>
                        <a href="#" data-action="delete" data-index={index} style={{ marginRight: 10 }} onClick={handleActionClick}>删除</a>
                        <a href="#" data-action="edit" data-index={index} onClick={handleActionClick}>编辑</a>
                    </>
                );
            },
        },
        {
            title: '保养人员',
            dataIndex: 'personName',
        },
        {
            title: '开始时间',
            dataIndex: 'maintainStartTime',
        },
        {
            title: '结束时间',
            dataIndex: 'maintainEndTime',
        },
        {
            title: '保养用时',
            dataIndex: 'wastedTime',
        },
        {
            title: '内容或步骤',
            dataIndex: 'contentOrSteps',
        },
    ];

    return (
        <BasicTable dataSource={data} columns={tableColumns} />
    );
}


/**
 * 主表单
 */
const MaintenanceProgramDetailForm1 = React.forwardRef(function MaintenanceProgramDetailForm1({ form, form: { getFieldDecorator, setFieldsValue, getFieldValue }, onEvent }, ref) {
    React.useImperativeHandle(ref, () => ({ form }));

    const [init, setInit] = useState(false);

    const [treeData1, setTreeData1] = useState([]); // 保养班组
    // const [treeData2, setTreeData2] = useState([]);
    const treeData2 = ['待保养', '保养中', '已完成'].map(item => ({
        title: item,
        value: item,
    })); // 保养状态
    const [treeData3, setTreeData3] = useState([]); // 保养级别
    const [treeData4, setTreeData4] = useState([]); // 外派单位

    const [isModal1Open, setIsModal1Open] = useState(false);
    const [selected1, setSelected1] = useState({ key: [], row: [] });

    const [table1Data, setTable1Data] = useState([]);

    const [isModal2Open, setIsModal2Open] = useState(false);
    const [modal2Data, setModal2Data] = useState({});

    const [table3Data, setTable3Data] = useState([]);

    const [isModal3Open, setIsModal3Open] = useState(false);
    const [modal3Data, setModal3Data] = useState({});

    // 保养工作量窗口
    const handleModal1Ok = useCallback(() => {
        // console.log(selected1);
        setTable1Data(prev => {
            const newData = [...prev];
            const ids = newData.map(item => item.personId);
            selected1.row.forEach(item => {
                ids.indexOf(item.id) === -1 && newData.push({
                    id: null,
                    personId: item.id,
                    personName: item.userName,
                    maintainStartTime: null,
                    maintainEndTime: null,
                    wastedTime: null,
                    contentOrSteps: null,
                });
            });
            return newData;
        });
        setIsModal1Open(false);
    }, [selected1]);
    const handleModal1Cancel = useCallback(() => {
        setIsModal1Open(false);
    }, []);
    const handleAddPersonClick = useCallback(() => {
        setIsModal1Open(true);
    }, []);

    // 保养工作量表格
    const handleTable1Event = useCallback((e) => {
        switch (e.type) {
            case 'EDIT_ITEM': {
                setModal2Data({
                    ...table1Data[e.index],
                    _index: e.index,
                });
                setIsModal2Open(true);
                break;
            }
            case 'DELETE_ITEM': {
                setTable1Data(prev => {
                    const newData = [...prev];
                    newData.splice(e.index, 1);
                    return newData;
                });
                break;
            }
            default:
                break;
        }
    }, [table1Data]);

    // 保养工作量 - 人员表格
    const handleTable2SelectChange = useCallback((selectedRowKeys, selectedRows) => {
        setSelected1({ key: selectedRowKeys, row: selectedRows });
    }, []);

    // 保养工作量 - 编辑人员
    const form1Ref = useRef();
    const Form1Wrap = Form.create({
        mapPropsToFields(props) {
            const { data } = props;
            return (data && data.personId) ? {
                id: Form.createFormField({ value: data.id }),
                personId: Form.createFormField({ value: data.personId }),
                personName: Form.createFormField({ value: data.personName }),
                maintainStartTime: Form.createFormField({ value: data.maintainStartTime ? moment(data.maintainStartTime) : null }),
                maintainEndTime: Form.createFormField({ value: data.maintainEndTime ? moment(data.maintainEndTime) : null }),
                wastedTime: Form.createFormField({ value: data.wastedTime }),
                contentOrSteps: Form.createFormField({ value: data.contentOrSteps }),
                _index: Form.createFormField({ value: data._index }),
            } : {};
        }
    })(MaintenanceProgramDetailForm1Form1);

    const handleModal2Ok = useCallback(() => {
        form1Ref.current.form.validateFields((err, values) => {
            if (err) {
                message.error('表单验证错误');
                return;
            }
            const { _index, ...rest } = values;
            setTable1Data(prev => {
                const newData = [...prev];
                newData.splice(_index, 1, {
                    ...rest,
                    maintainStartTime: formatTime(rest.maintainStartTime),
                    maintainEndTime: formatTime(rest.maintainEndTime),
                });
                return newData;
            });
            setIsModal2Open(false);
        });
    }, []);
    const handleModal2Cancel = useCallback(() => {
        setIsModal2Open(false);
    }, []);

    // 保养部位表格
    const handleTable3Event = useCallback((e) => {
        switch (e.type) {
            case 'EDIT_ITEM': {
                setModal3Data({
                    ...table3Data[e.index],
                    _index: e.index,
                });
                setIsModal3Open(true);
                break;
            }
            default:
                break;
        }
    }, [table3Data]);

    // 保养部位 - 编辑窗口
    const form2Ref = useRef();
    const Form2Wrap = Form.create({
        mapPropsToFields(props) {
            const { data } = props;
            return (data && data.id) ? {
                id: Form.createFormField({ value: data.id }),
                requirementId: Form.createFormField({ value: data.requirementId }),
                status: Form.createFormField({ value: data.status }),
                typeId: Form.createFormField({ value: data.typeId }),
                typeName: Form.createFormField({ value: data.typeName }),
                positionName: Form.createFormField({ value: data.positionName }),
                maintainStandard: Form.createFormField({ value: data.maintainStandard }),
                maintain: Form.createFormField({ value: data.maintain }),
                remarks: Form.createFormField({ value: data.remarks }),
                _index: Form.createFormField({ value: data._index }),
            } : {};
        }
    })(MaintenanceProgramDetailForm1Form2);

    const handleModal3Ok = useCallback(() => {
        form2Ref.current.form.validateFields((err, values) => {
            if (err) {
                message.error('表单验证错误');
                return;
            }
            const { _index, ...rest } = values;
            setTable3Data(prev => {
                const newData = [...prev];
                newData.splice(_index, 1, rest);
                return newData;
            });
            setIsModal3Open(false);
        });
    }, []);
    const handleModal3Cancel = useCallback(() => {
        setIsModal3Open(false);
    }, []);

    // 其它
    const handleSubmitClick = useCallback(() => {
        form.validateFields((err, values) => {
            if (err) {
                message.error('表单验证错误');
                return;
            }
            onEvent && onEvent({ type: 'FORM_SUBMIT', value: values });
        });
    }, [onEvent]);

    const handleCancelClick = useCallback(() => {
        onEvent && onEvent({ type: 'FORM_CANCEL' });
    }, [onEvent]);

    const handleStartTimeChange = useCallback((date, dateStr) => {
        const endTime = getFieldValue('maintainEndTime');
        if (!endTime || date > endTime) {
            setFieldsValue({
                wastedTime: null,
            });
            return;
        }
        const m = Math.floor((endTime - date) / 1000 / 60);
        setFieldsValue({
            wasteTime: `${Math.floor(m / 60)}小时${m % 60}分`,
        });
    }, []);

    const handleEndTimeChange = useCallback((date, dateStr) => {
        const startTime = getFieldValue('maintainStartTime');
        if (!startTime || startTime > date) {
            setFieldsValue({
                wastedTime: null,
            });
            return;
        }
        const m = Math.floor((date - startTime) / 1000 / 60);
        setFieldsValue({
            wasteTime: `${Math.floor(m / 60)}小时${m % 60}分`,
        });
    }, []);

    useEffect(() => {
        init && setFieldsValue({
            equipmentMaintainWorkVOList: table1Data,
        });
    }, [table1Data]);

    useEffect(() => {
        init && setFieldsValue({
            equipmentMaintainPositionVOList: table3Data,
        });
    }, [table3Data]);

    useEffect(() => {
        // console.log('init form:', form.getFieldsValue());
        setTable1Data(getFieldValue('equipmentMaintainWorkVOList'));
        setTable3Data(getFieldValue('equipmentMaintainPositionVOList'));

        (async () => {
            try {
                const res1 = await get(euqApplicationName + '/currency/queryTeam');
                res1 && setTreeData1(res1.data.map(item => {
                    return {
                        title: item.name,
                        value: item.id,
                    };
                }));
            } catch (err) {}
        })();
        (async () => {
            try {
                const res3 = await get(euqApplicationName + '/api/findEquipmentNextParameterPageList?typeId=6');
                res3 && setTreeData3(res3.data.map(item => {
                    return {
                        title: item.configValue.trim(),
                        value: item.id,
                    };
                }));
            } catch (err) {}
        })();
        (async () => {
            try {
                const res4 = await get(euqApplicationName + '/parameter_setting_public/queryRentDepartmentList', { params: { type: 1 } });
                res4 && setTreeData4(res4.data.map(item => ({
                    value: item.id,
                    title: item.name,
                })));
            } catch (err) {}
        })();

        setInit(true);
    }, []);

    return (
        <>
            <Form layout="horizontal" labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
                <Title level={4}>设备信息</Title>
                <Row>
                    <Col span={6}>
                        <Form.Item label="设备编号">
                            {getFieldDecorator("equipmentCode")(
                                <Input disabled />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="设备名称">
                            {getFieldDecorator("equipmentName")(
                                <Input disabled />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="规格型号">
                            {getFieldDecorator("specsModel")(
                                <Input disabled />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="设备类别">
                            {getFieldDecorator("typeName")(
                                <Input disabled />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="使用部门">
                            {getFieldDecorator("equipmentDepart")(
                                <Input disabled />
                            )}
                        </Form.Item>
                    </Col>
                </Row>
                {getFieldDecorator("equipmentId")(
                    <Input type="hidden" disabled />
                )}

                <Title level={4}>保养信息</Title>
                <Row>
                    <Col span={6}>
                        <Form.Item label="保养班组">
                            {getFieldDecorator("maintainTeamId")(
                                <TreeSelect treeData={treeData1} />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="保养状态">
                            {getFieldDecorator("maintainPlanStatus", {
                                initialValue: '待保养',
                            })(
                                <TreeSelect treeData={treeData2} />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="保养级别">
                            {getFieldDecorator("maintainLevelId")(
                                <TreeSelect treeData={treeData3} />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="外派单位">
                            {getFieldDecorator("outSourceId")(
                                <TreeSelect treeData={treeData4} />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="开始时间">
                            {getFieldDecorator("maintainStartTime")(
                                <DatePicker showTime style={{ width: '100%' }} onChange={handleStartTimeChange} />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="结束时间">
                            {getFieldDecorator("maintainEndTime")(
                                <DatePicker showTime style={{ width: '100%' }} onChange={handleEndTimeChange} />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="保养用时">
                            {getFieldDecorator("wasteTime")(
                                <Input disabled />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="保养费用">
                            {getFieldDecorator("cost")(
                                <InputNumber />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={24}></Col>
                    <Col span={6}>
                        <Form.Item label="是否停机">
                            {getFieldDecorator("isStop")(
                                <Radio.Group>
                                    <Radio value={0}>是</Radio>
                                    <Radio value={1}>否</Radio>
                                </Radio.Group>
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="停机时长">
                            {getFieldDecorator("stopTime")(
                                <InputNumber disabled={getFieldValue('isStop') === 1} />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={24}>
                        <Form.Item label="工作描述" labelCol={{ span: 2 }} wrapperCol={{ span: 22 }}>
                            {getFieldDecorator("description")(
                                <TextArea rows={4} />
                            )}
                        </Form.Item>
                    </Col>
                </Row>

                <Title level={4} style={{ marginTop: 15 }}>保养工作量</Title>
                <Button type="primary" icon="plus" onClick={handleAddPersonClick}>增加人员</Button>
                <MaintenanceProgramDetailForm1Table1 data={table1Data} onEvent={handleTable1Event} />
                {getFieldDecorator('equipmentMaintainWorkVOList', {
                    initialValue: [],
                })(
                    <Input type="hidden" />
                )}

                <Title level={4} style={{ marginTop: 15 }}>保养部位</Title>
                <MaintenanceProgramDetailForm1Table3 data={table3Data} onEvent={handleTable3Event} />
                {getFieldDecorator('equipmentMaintainPositionVOList', {
                    initialValue: [],
                })(
                    <Input type="hidden" />
                )}

                {getFieldDecorator("id")(
                    <Input type="hidden" />
                )}

                <div style={{ marginTop: 20 }}>
                    <Button type="primary" style={{ marginRight: 5 }} onClick={handleSubmitClick}>保存</Button>
                    <Button onClick={handleCancelClick}>取消</Button>
                </div>
            </Form>
            <Modal title="增加人员" width={880} visible={isModal1Open} onOk={handleModal1Ok} onCancel={handleModal1Cancel}>
                <MaintenanceProgramDetailForm1Table2 selectedKeys={selected1.key} onSelectChange={handleTable2SelectChange} treeData1={treeData1} />
            </Modal>
            <Modal title="编辑人员" visible={isModal2Open} onOk={handleModal2Ok} onCancel={handleModal2Cancel}>
                <Form1Wrap wrappedComponentRef={form1Ref} data={modal2Data} />
            </Modal>
            <Modal title="编辑部位" visible={isModal3Open} onOk={handleModal3Ok} onCancel={handleModal3Cancel}>
                <Form2Wrap wrappedComponentRef={form2Ref} data={modal3Data} />
            </Modal>
        </>
    );
});

/**
 * 主组件
 */
function MaintenanceProgramDetail2() {
    const { id } = useParams();
    const history = useHistory();

    const [isDataLoading, setIsDataLoading] = useState(true);
    const [formData, setFormData] = useState({});

    // 主表单
    const Form1Wrap = useMemo(() => {
        return Form.create({
            mapPropsToFields(props) {
                const { data } = props;
                return (data && data.id) ? {
                    id: Form.createFormField({ value: data.id }),
                    equipmentCode: Form.createFormField({ value: data.equipmentCode }),
                    equipmentName: Form.createFormField({ value: data.equipmentName }),
                    specsModel: Form.createFormField({ value: data.specsModel }),
                    typeName: Form.createFormField({ value: data.typeName }),
                    equipmentDepart: Form.createFormField({ value: data.equipmentDepart }),
                    equipmentId: Form.createFormField({ value: data.equipmentId }),
                    maintainTeamId: Form.createFormField({ value: data.maintainTeamId }),
                    maintainTeamName: Form.createFormField({ value: data.maintainTeamName }),
                    // maintainPlanStatus: Form.createFormField({ value: data.maintainPlanStatus }),
                    maintainLevelId: Form.createFormField({ value: data.maintainLevelId }),
                    outSourceId: Form.createFormField({ value: data.outSourceId }),
                    maintainStartTime: Form.createFormField({ value: data.maintainStartTime ? moment(data.maintainStartTime) : null }),
                    maintainEndTime: Form.createFormField({ value: data.maintainEndTime ? moment(data.maintainEndTime) : null }),
                    cost: Form.createFormField({ value: data.cost }),
                    isStop: Form.createFormField({ value: data.isStop }),
                    stopTime: Form.createFormField({ value: data.stopTime }),
                    description: Form.createFormField({ value: data.description }),
                    equipmentMaintainPositionVOList: Form.createFormField({ value: data.equipmentMaintainPositionVOList || [] }),
                    equipmentMaintainWorkVOList: Form.createFormField({ value: data.equipmentMaintainWorkVOList || [] }),
                } : {};
            }
        })(MaintenanceProgramDetailForm1);
    }, [formData]);

    const handleForm1Event = useCallback((e) => {
        switch (e.type) {
            case 'FORM_SUBMIT': {
                /*const reqData = {
                    ...e.value,
                    maintainStartTime: formatTime(e.value.maintainStartTime),
                    maintainEndTime: formatTime(e.value.maintainEndTime),
                };
                // console.log(reqData); return;
                (async () => {
                    try {
                        const res = await post(euqApplicationName + '/equipmentMaintainPlan/executeEquipmentMaintainPlan', { data: reqData });
                        message.info('计划执行成功');
                        history.replace('/MaintenanceProgram');
                    } catch (err) {}
                })();*/
                (async () => {
                    try {
                        if (e.value.maintainPlanStatus === '已完成') {
                            const currentTime = await getCurrentTime();
                            const currentMoment = moment(currentTime);

                            if (!e.value.maintainStartTime || !e.value.maintainEndTime) {
                                Modal.error({
                                    content: '当状态为已完成时，必须填写开始时间和结束时间',
                                });
                                return;
                            }
                            if (currentMoment < moment(e.value.maintainEndTime)) {
                                Modal.error({
                                    content: '当状态为已完成时，结束时间必须小于当前时间',
                                });
                                return;
                            }
                            for (const workItem of e.value.equipmentMaintainWorkVOList) {
                                if (!workItem.maintainStartTime || !workItem.maintainEndTime || moment(workItem.maintainStartTime) < e.value.maintainStartTime || moment(workItem.maintainEndTime) > e.value.maintainEndTime) {
                                    Modal.error({
                                        content: '当状态为已完成时，保养人员的开始时间和结束时间必须介于工单的开始时间和结束时间之间',
                                    });
                                    return;
                                }
                            }
                        }

                        const reqData = {
                            ...e.value,
                            maintainStartTime: formatTime(e.value.maintainStartTime),
                            maintainEndTime: formatTime(e.value.maintainEndTime),
                        };
                        // console.log(reqData); return;

                        await post(euqApplicationName + '/equipmentMaintainPlan/executeEquipmentMaintainPlan', { data: reqData });
                        message.info('计划执行成功');
                        history.replace('/MaintenanceProgram');
                    } catch (err) {
                        err && console.error(err);
                    }
                })();
                break;
            }
            case 'FORM_CANCEL': {
                history.goBack();
                break;
            }
            default:
                break;
        }
    }, []);

    const getCurrentTime = useCallback(async () => {
        const res = await get(euqApplicationName + '/equipmentMaintain/getCurrentTime');
        return res.data.time;
    }, []);

    useEffect(() => {
        (async () => {
            try {
                const res = await get(euqApplicationName + '/equipmentMaintainPlan/findExecuteEquipmentMaintainPlan', { params: { planId: id } });
                if (res && res.data.length > 0) {
                    setFormData(res.data[0]);
                    setIsDataLoading(false);
                } else {
                    Modal.error({
                        title: '未找到保养计划',
                        onOk() {
                            history.goBack();
                        },
                    });
                }
            } catch (err) {}
        })();
    }, []);

    return (
        <>
            <h4>执行计划</h4>
            <Card size="small" style={{ position: 'relative' }}>
                <Form1Wrap data={formData} onEvent={handleForm1Event} />
                {isDataLoading && (
                    <div className="x-cover-loading2">
                        <Spin size="large" />
                    </div>
                )}
            </Card>
        </>
    );
}

export default MaintenanceProgramDetail2;
